package com.sq.springcloud.controller;

import com.sq.springcloud.entities.CommontResult;
import com.sq.springcloud.entities.Payment;
import com.sq.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.apache.http.impl.client.HttpClients;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URI;
import java.util.List;

/**
 * @Description: TODO
 * @author: ydy
 * @date: 2022-09-02 11:39
 */
@RestController
@Slf4j
public class OrderController {

//    public static final String PAYMENT_URL = "http://localhost:8001";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    public OrderController() {
    }

    @PostMapping(value = "/consumer/payment/add")
    public CommontResult<Payment> add(@RequestBody Payment payment){
        return restTemplate.postForObject(PAYMENT_URL + "/payment/add", payment, CommontResult.class);
    }

    //getForObject返回对象响应体中data数据转化成的对象，基本可以理解为json数据格式返回。
    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommontResult<Payment> get(@PathVariable(value = "id") Long id){
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommontResult.class);
    }

    //forEntity返回对象为ResponseEntity对象，包括了响应中的一些重要信息，比如响应头、响应状态码、响应体等。
    @GetMapping(value = "/consumer/payment/getForEntity/{id}")
    public CommontResult<Payment> get2(@PathVariable(value = "id") Long id){
        //return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommontResult.class);
        ResponseEntity<CommontResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommontResult.class);
        if(forEntity.getStatusCode().is2xxSuccessful()){
            log.info("*************" + forEntity.getStatusCode() + "\t" + forEntity.getHeaders());
            return forEntity.getBody();
        }else{
            return new CommontResult<>(444,"操作失败");
        }
    }

   //使用HttpClient
    @GetMapping(value = "/consumer/payment/getByHttpClient/{id}")
    public String getByHttpClient(@PathVariable(value = "id") Long id){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        HttpGet httpGet = new HttpGet(PAYMENT_URL + "/payment/get/" + id);
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @GetMapping(value = "/consumer/payment/lb")
    public String getPayment(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances == null || instances.size() <= 0){
            return null;
        }
        ServiceInstance instance = loadBalancer.instance(instances);
        URI uri = instance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }
}
